/*
 * @Description: 请求
 * @Version: 1.0
 * @Autor: jiajun wu
 * @Date: 2021-11-24 09:32:56
 * @LastEditors: jiajun wu
 * @LastEditTime: 2021-12-02 18:01:01
 */
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, Canceler } from "axios";
import store from "@/store";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import notification from 'ant-design-vue/es/notification'
import { getToken } from "./util";
import { ResDataStruct } from "@/interface/request";
import { Cookie, SessionStorage } from "./storage";
import config from '@/config/config'

const service = axios.create({
  baseURL: config.context || '',
  timeout: 60000
})

const err = (error: { request: AxiosRequestConfig, response: AxiosResponse }) => {
  if (error.response) {
    const data: ResDataStruct = error.response.data;
    const token = getToken()
    if (error.response.status === 404) {
      notification.error({
        message: "NotFound",
        description: data.message
      })
    } else if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    } else if (error.response.status === 402) {
      notification.error({
        message: 'License验证失败',
        description: data.message
      })
    } else if (error.response.status === 401) {
      notification.error({
        message: '未经授权',
        description: '授权验证失败'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      } else {
        window.location.href = "#/login"
      }
    } else if (error.response.status === 400) {
      notification.error({
        message: '错误',
        description: data.message
      })
    } else if (error.response.status === 500) {
      notification.error({
        message: '服务器错误',
        description: "服务器错误"
      })
    }
  }
  return Promise.reject(error)
}

service.interceptors.request.use((config) => {
  const token: string = SessionStorage.get(ACCESS_TOKEN)
  if (token) {
    Cookie.set(ACCESS_TOKEN, token);
  }

  // 将请求存储起来 跳转下一页时中断未完成的请求
  config.cancelToken = new axios.CancelToken((c: Canceler) => {
    store.dispatch("addHttpRequestList", c)
  });

  return config
}, err)

service.interceptors.response.use((response) => {
  return response
}, err)


export default service
